package br.com.nooclix.salon.servlet;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.nooclix.salon.application.AttendanceSheetApplication;
import br.com.nooclix.salon.application.EmployeeApplication;
import br.com.nooclix.salon.domain.attendance.ReportAttendance;
import br.com.nooclix.salon.domain.employee.Employee;
import br.com.nooclix.salon.infrastructure.util.ApplicationContextRegister;
import br.com.nooclix.salon.servlet.util.UtilitysServlet;

public class ComissionReportServlet extends HttpServlet {

	private AttendanceSheetApplication attendanceSheetRepositoryImpl = ApplicationContextRegister
			.getBean("attendanceSheetApplication",
					AttendanceSheetApplication.class);

	private EmployeeApplication employeeApplication = ApplicationContextRegister
			.getBean("employeeApplication", EmployeeApplication.class);

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");

		RequestDispatcher dispatcher = req
				.getRequestDispatcher("reports/comissionReport.jsp");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");

		String codeEmplooyee = req.getParameter("code");
		
		String dayStart = req.getParameter("dStart");
		String mouthStart = req.getParameter("mStart");
		String yearStart = req.getParameter("yStart");

		Calendar calStart = UtilitysServlet.createDateByValues(Integer
				.parseInt(dayStart), Integer.parseInt(mouthStart), Integer
				.parseInt(yearStart));

		String dayEnd = req.getParameter("dEnd");
		String mouthEnd = req.getParameter("mEnd");
		String yearEnd = req.getParameter("yEnd");

		Calendar calEnd = UtilitysServlet.createDateByValues(Integer
				.parseInt(dayEnd), Integer.parseInt(mouthEnd), Integer
				.parseInt(yearEnd));

		req.setAttribute("report", findAttendancesByEmployee(Integer
				.parseInt(codeEmplooyee), calStart, calEnd));
		
		req.setAttribute("dateStart", calStart.getTime());
		
		req.setAttribute("dateEnd", calEnd.getTime());

		dispatcher.forward(req, resp);
	}

	private List<ReportAttendance> findAttendancesByEmployee(Integer code,
			Calendar start, Calendar end) {
		Employee employee = findEmployeeById(code);
		List<ReportAttendance> l = attendanceSheetRepositoryImpl
				.findReportEmployeeAndPeriod(employee, start, end);
		
		return l;

	}

	private Employee findEmployeeById(Integer id) {

		return employeeApplication.findById(id);

	}

}